#include <windows.h>
#include <stdio.h>
#include "api.h"
#include "image.h"
#include "data.h"
#include "tools.h"
#include "buttonswnd.h"
#include "resource.h"

#define BM_TOOLBUTTONS WM_USER+1

#define toolClassName "TOOLWND"

extern TOOL_CALLBACK toolCallback[];

extern PDATA data;

typedef struct _TOOLWND_{
	HWND hwndButtons;
	int currentIndex;
	PDATA data;
} *PTOOLWND, TOOLWND;

void toolWndOnCreate(HWND hwnd, PTOOLWND data){
	data->hwndButtons = buttonsWndCreate(hwnd, 0, 0,IDB_TOOLS, 20, 20, BM_TOOLBUTTONS);
	buttonsSetSelected(data->hwndButtons, data->currentIndex);
}

LRESULT CALLBACK toolWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam){
	GET_DATA(PTOOLWND);
	switch(message){
	case WM_CREATE:
		toolWndOnCreate(hwnd, data);
		break;
	case BM_TOOLBUTTONS:
		data->currentIndex = wParam;
		::data->currentTool(NULL, ::data, TOOL_LOSTFOCUS, NULL);
		buttonsSetSelected(data->hwndButtons, wParam);
		::data->currentTool = toolCallback[wParam];
		::data->currentTool(NULL, ::data, TOOL_GETFOCUS, NULL);
		break;
	case WM_DESTROY:
		FREE_DATA();
		break;
	}
	return DefWindowProc(hwnd, message, wParam, lParam);
}

HWND toolWndCreate(HWND hwndParent, int x, int y, int dx, int dy, PDATA appData)
{
    HWND hwnd;
	static BOOLEAN isRegistered = FALSE;
	HINSTANCE hInstance = (HINSTANCE)GetWindowLong(hwndParent, GWL_HINSTANCE);
	if (!isRegistered){
		apiRegisterControlWnd(hInstance, toolClassName, toolWndProc);
		isRegistered = TRUE;
	}

	NEW_DATA(TOOLWND);
	data->data = appData;
	data->currentIndex = 0;
	::data->currentTool = toolCallback[data->currentIndex];
    hwnd = CreateWindowEx(0,
           toolClassName,
           "",
           WS_VISIBLE | WS_CLIPCHILDREN | WS_CHILD,
           x,
           y,
           dx,
           dy,		   
           hwndParent,
           NULL,
           hInstance,
		   data
           );
    ShowWindow (hwnd, SW_SHOW);
    return hwnd;
}
